<template>
  <div>
    <div class="course-box">
      <i-card
        :title="course.title"
        :extra="course.subjectTitle"
        :thumb="course.cover"
      >
        <div slot="footer">{{ course.description }}</div>
      </i-card>
    </div>
    <div class="chapter-box">
      <i-panel title="课程内容">
        <div class="chapter" v-for="(item, index) in chapter" :key="index">
          {{ item.title }}
          <div class="video" v-for="(video, idx) in item.videos" :key="idx">
            <i-icon type="live" />{{ video.title }}
          </div>
        </div>
      </i-panel>
    </div>

    <div class="buy-box" v-if="!status">
      <van-submit-bar
        :price="course.price * 100"
        button-text="立刻购买"
        @submit="onSubmit"
      />
    </div>
    <div class="buy-box" v-if="status">
      <van-submit-bar
        :price="course.price * 100"
        button-text="立刻观看"
        @submit="play"
      />
    </div>
  </div>
</template>

<script>
import request from "../../../utils/request";

export default {
  data() {
    return {
      course: {},
      chapter: [],
      courseId: "",
      userId: "",
      order: {},
      status: "",
    };
  },

  onLoad: function (option) {
    this.courseId = option.id;
    this.userId = wx.getStorageSync("id");

    this.getCourse();
    this.getChapter();
    this.getPurchaseStatus();
  },

  methods: {
    async getCourse() {
      let response = await request({
        url: `/course_service/course/getCourseInfoById/${this.courseId}`,
        method: "GET",
      });

      this.course = response.data.item;
    },

    async getChapter() {
      let response = await request({
        url: `/course_service/chapter/getChapterInfo/${this.courseId}`,
        method: "GET",
      });

      this.chapter = response.data.list;
    },

    async getPurchaseStatus() {
      let response = await request({
        url: `/order_service/getPurchaseStatus/${this.userId}/${this.courseId}`,
        method: "GET",
      });

      console.log(response);
      if (response.success === true) {
        this.status = true;
      } else {
        this.status = false;
      }
    },

    async onSubmit() {
      this.order.userId = this.userId;
      this.order.courseId = this.courseId;
      this.order.fee = this.course.price;

      console.log(this.order);
      let response = await request({
        url: `/order_service/pay`,
        method: "POST",
        data: this.order,
      });

      if (response.success === true) {
        this.status = true;
      }
    },

    async play() {
      wx.navigateTo({
        url: "/pages/player/main",
      });
    },
  },
};
</script>

<style>
.course-box {
  margin-top: 5%;
}
.chapter-box {
  margin-left: 5%;
  margin-right: 5%;
}
.chapter {
  margin: 3%;
  font-size: 30rpx;
}
.video {
  font-size: 25rpx;
  margin-left: 5%;
  margin-right: 5%;
  margin-top: 2%;
  margin-bottom: 2%;
  border-color: blue;
}
</style>
